package net.lovesrc.support.service.proxy;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.kevinsawicki.http.HttpRequest;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zhouzhou.fastjava.util.ThreadKit;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;

public class DLJLProxyHostService implements ProxyHostService {

    private static final Logger logger = LoggerFactory.getLogger(DLJLProxyHostService.class);

    @Override
    public List<ProxyHost> getProxies(String province, String city) {

        Map<String, String> parameters = Maps.newHashMap();
        parameters.put("method", "proxyServer.ipinfolist");
        parameters.put("quantity", "10");
        parameters.put("anonymous", "1");
        parameters.put("ms", "1");
        parameters.put("service", "0");
        parameters.put("protocol", "1");
        parameters.put("wdsy", "on");
        parameters.put("format", "json");
        parameters.put("separator", "1");
        parameters.put("separator_txt", "");
        parameters.put("distinct", "true");
        parameters.put("province", province + "省");
        if (StringUtils.isNotBlank(city)) {
            parameters.put("city", city + "市");
        }
        String body;
        while (true) {
            HttpRequest proxyAddressRequest = HttpRequest.get("http://open.ipjldl.com/index.php/api/entry", parameters, true);
            body = proxyAddressRequest.body();
            if (body.contains("请求太频繁")) {
                ThreadKit.sleepSeconds(2);
                continue;
            }
            break;
        }
        logger.info("Body: {}", body);
        JSONObject rootJson = JSON.parseObject(body);
        int ret = rootJson.getIntValue("ret");
        if (ret == 200) {
            JSONObject data = rootJson.getJSONObject("data");
            if (data.getIntValue("code") == 0) {
                JSONObject list = data.getJSONObject("list");
                List<ProxyHost> candinates = Lists.newArrayList();
                JSONArray proxyIpInfoList = list.getJSONArray("ProxyIpInfoList");
                if (proxyIpInfoList != null) {
                    proxyIpInfoList.forEach(r -> {
                        JSONObject t = (JSONObject) r;
                        ProxyHost host = new ProxyHost(t.getString("IpAddress"), t.getString("IP"), t.getIntValue("Port"));
                        candinates.add(host);
                    });
                }
                if (candinates.isEmpty() && StringUtils.isNotBlank(city)) {
                    return this.getProxies(province, StringUtils.EMPTY);
                }
                return candinates;
            }
        }
        return null;
    }

}
